﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WMS_Goodsinfo.Api.Read.Application.Command;
using WMS_Goodsinfo.Api.Read.DTOS;
using WMS_Goodsinfo.Domain;
using WMS_Goodsinfo.ErrorCode;
using WMS_Goodsinfo.Infastructure;

namespace WMS_Goodsinfo.Api.Read.Application.Handler
{
    public class GetProductListHandler : IRequestHandler<GetProductListCommand, ApiPaging<ProductDtoList>>
    {
        private readonly IProductRepository<Product_Table> _productRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetProductListHandler> logger;

        public GetProductListHandler(IProductRepository<Product_Table> productRepository, IMapper mapper, ILogger<GetProductListHandler> logger)
        {
            _productRepository = productRepository;
            _mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 查询商品列表（支持分页和过滤）
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页商品列表</returns>
        public async Task<ApiPaging<ProductDtoList>> Handle(GetProductListCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<ProductDtoList>();
            
            try
            {
                // 基础查询：获取未删除的商品
                var query = _productRepository.GetAll().Where(p => !p.IsDelete);

                // 应用过滤条件
                if (!string.IsNullOrWhiteSpace(request.ProductName))
                {
                    query = query.Where(p => p.ProductName.Contains(request.ProductName));
                }

                if (!string.IsNullOrWhiteSpace(request.ProductTypeId))
                {
                    query = query.Where(p => p.ProductTypeId == request.ProductTypeId);
                }

                if (!string.IsNullOrWhiteSpace(request.UnitName))
                {
                    query = query.Where(p => p.UnitName == request.UnitName);
                }

                if (!string.IsNullOrWhiteSpace(request.Barcode))
                {
                    query = query.Where(p => p.Barcode.Contains(request.Barcode));
                }

                if (!string.IsNullOrWhiteSpace(request.Inventory))
                {
                    query = query.Where(p => p.Inventory == request.Inventory);
                }
                // 应用日期范围过滤（基于创建时间）
                if (request.StartTime.HasValue)
                {
                    query = query.Where(p => p.CreateTime >= request.StartTime.Value);
                }
                if (request.EndTime.HasValue)
                {
                    // 将结束日期设置为当天
                    var endDate = request.EndTime.Value.Date.AddDays(1).AddSeconds(-1);
                    query = query.Where(p => p.CreateTime <= endDate);
                }

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);
                
                // 计算总页数
                var totalPage = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 应用分页和排序
                var products = await query
                    .OrderByDescending(p => p.CreateTime) // 按创建时间倒序
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 使用AutoMapper映射到DTO
                var productDtos = _mapper.Map<List<ProductDtoList>>(products);

                // 设置返回结果
                result.Code = StatusEnum.OK;
                result.Message = "查询成功";
                result.TotalCount = totalCount;
                result.TotalPage = totalPage;
                result.PageData = productDtos;
                logger.LogInformation("获取商品列表数据成功");
            }
            catch (Exception ex)
            {
                result.Code = StatusEnum.Error;
                result.Message = $"查询失败: {ex.Message}";
                result.TotalCount = 0;
                result.TotalPage = 0;
                result.PageData = new List<ProductDtoList>();
                logger.LogError("获取商品列表数据失败");
            }

            return result;
        }
    }
}
